//
//  Application.m
//  MHO
//
//  Created by papo on 2/17/14.
//  Copyright (c) 2014 maihoang. All rights reserved.
//

#import "Application.h"
#import "Lib.h"
#import "Contants.h"
#import "ServiceLib.h"
#import "SBJson.h"
#import "NSString+HTML.h"

@implementation Application


+ (Application*)appFromDictionary:(NSDictionary *)dict {
    return [[self alloc] initWithDictionary:dict];
}

+ (NSArray*)getGameHot {
    //http://mobile.mho.vn/services/game?IdSystem=2&IdGroup=1&Count=10&key=mho123190456$@!
    NSString* url = [NSString stringWithFormat:@"http://mobile.mho.vn/services/game?IdSystem=2&IdGroup=1&Count=5&key=%@", kServerKey];
    return [self appsFromServiceUrl:url];
//    return [self appsFromServiceUrl:[Contants gameUrlWithCategory:kGroupGame idSystem:kPlatformIos idGroup:0 isHot:1 isNew:0 mostView:0 pageIndex:0 pageSize:5 key:kServerKey]];
}

+ (NSArray*)getGameTopGroup:(NSInteger)group count:(NSInteger)count {
    return [self appsFromServiceUrl:[Contants gameUrlForKey:[NSString stringWithFormat:kServiceGameTop, kPlatformIos, group, count, kServerKey]]];
}

+ (NSArray*)appsFromServiceUrl:(NSString *)url {
    NSMutableArray* array = [[NSMutableArray alloc] init];
    
    NSString* retV = [ServiceLib sendGetRequest:url];
    if (retV) {
        SBJsonParser* parser = [[SBJsonParser alloc] init];
        id data = [parser objectWithString:retV];
        if (data && [data isKindOfClass:[NSArray class]]) {
            [self setArray:array from:data];
        }
        else if (data && [data isKindOfClass:[NSDictionary class]]) {
            id list = [data objectForKey:@"DataList"];
            if (list && [list isKindOfClass:[NSArray class]]) {
                [self setArray:array from:list];
            }
            else {
                list = [data objectForKey:@"Data"];
                if (list && [list isKindOfClass:[NSArray class]]) {
                    [self setArray:array from:list];
                }
            }
        }
    }
    
    return array;
}

+ (Application*)appDetail {
    Application* app;
    return app;
}

+ (void)setArray:(NSMutableArray*)array from:(NSArray*)data {
    for (id appDict in data) {
        if (appDict && [appDict isKindOfClass:[NSDictionary class]]) {
            Application* app = [Application appFromDictionary:appDict];
            if (app) {
                [array addObject:app];
            }
        }
    }
}

+ (BOOL)sendRate:(NSString *)appId rate:(NSInteger)rate {
    NSString* url = [NSString stringWithFormat:@"http://mobile.mho.vn/services/Rating?IdGame=%@&Rating=%ld&key=mho123190456$@!", appId, (long)rate];

    NSString* retVal = [ServiceLib sendGetRequest:url];
    if (retVal) {
        return YES;
    }
    return NO;
}

- (BOOL)sendRate:(NSInteger)rate {
    return [Application sendRate:self.appId rate:rate];
}

- (id)initWithDictionary:(NSDictionary *)dict {
    if (self = [super init]) {
        self.appId = numberCheckNull([dict objectForKey:kAppModelId]);
        self.appName = strCheckNull([dict objectForKey:kAppModelName]);
        self.descHtml = strCheckNull([dict objectForKey:kAppModelDesc]);
//        self.description = [self.descHtml stringByConvertingHTMLToPlainText];
        self.detailHtml = strCheckNull([dict objectForKey:kAppModelDetail]);
        self.detail = [self.detailHtml stringByConvertingHTMLToPlainText];
        self.imagePath = strCheckNull([dict objectForKey:kAppModeImagePath]);
        self.logoPath = strCheckNull([dict objectForKey:kAppModelLogoPath]);
        self.appPlatformId = strCheckNull([dict objectForKey:kAppModelPlatformId]);
        self.appPlatformName = strCheckNull([dict objectForKey:kAppModelPlatformName]);
        self.urlHomePage = strCheckNull([dict objectForKey:kAppModelUrlHomePage]);
        self.publisherId = strCheckNull([dict objectForKey:kAppModelPublisherId]);
        self.publisherName = strCheckNull([dict objectForKey:kAppModelPublisherName]);
        self.totalComment = [numberCheckNull([dict objectForKey:kAppModelTotalComment]) integerValue];
        self.totalDownload = [numberCheckNull([dict objectForKey:kApppModelTotalDownload]) integerValue];
        self.totalPoint = [numberCheckNull([dict objectForKey:kAppModelTotalPoint]) integerValue];
        self.totalVote = [numberCheckNull([dict objectForKey:kAppModelTotalVote]) integerValue];
        self.size = strCheckNull([dict objectForKey:kAppModelSize]);
        self.rate = [numberCheckNull([dict objectForKey:kAppModelRate]) intValue];
        self.like = [numberCheckNull( [dict objectForKey:kAppModelLike]) intValue];
        
        self.view = numberCheckNull([dict objectForKey:kAppModelView]);
        self.pictureAlbum = strCheckNull([dict objectForKey:kAppModelPictureAlbum]);
        [self scanPictureAlbumImages];
        self.file = strCheckNull([dict objectForKey:kAppModelFile]);

        self.versionApp = strCheckNull([dict objectForKey:kAppModelVersion]);
        self.plist = strCheckNull([dict objectForKey:@"plist"]);

    }
    return self;
}

- (void)scanPictureAlbumImages {
    
    if (!self.pictureAlbum) {
        NSLog(@"no image in album!");
        return;
    }
    
    if (!_pictureAlbumUrls) {
        _pictureAlbumUrls = [[NSMutableArray alloc] init];
    }
    NSString* url = nil;
    NSScanner *theScanner = [NSScanner scannerWithString:self.pictureAlbum];
    // find start of IMG tag
    [theScanner scanUpToString:@"<img" intoString:nil];
    while (![theScanner isAtEnd]) {
        [theScanner scanUpToString:@"src" intoString:nil];
        NSCharacterSet *charset = [NSCharacterSet characterSetWithCharactersInString:@"\"'"];
        [theScanner scanUpToCharactersFromSet:charset intoString:nil];
        [theScanner scanCharactersFromSet:charset intoString:nil];
        [theScanner scanUpToCharactersFromSet:charset intoString:&url];
        // "url" now contains the URL of the img
        if (url && url.length > 0) {
            url = [NSString stringWithFormat:@"http://mobile.mho.vn%@", url];
            NSURL* imageUrl = [NSURL URLWithString:url];
            [self.pictureAlbumUrls addObject:imageUrl];
        }
    }
}

//+ (NSString)

+ (BOOL)updateDownloadCountForId:(NSString *)appId {
    NSString* url = [NSString stringWithFormat:@"http://mobile.mho.vn/services/gameex?type=incdownload&g=%@&key=%@", appId, kServerKey];

    NSString* retVal = [ServiceLib sendGetRequest:url];
    if (retVal) {
        SBJsonParser* parser = [[SBJsonParser alloc] init];
        id data = [parser objectWithString:retVal];
        if (data && [data isKindOfClass:[NSDictionary class]]) {
            NSNumber* result = [data objectForKey:@"Ret"];
            if (result && result.intValue == 1) {
                return YES;
            }
        }
    }

    return NO;
}

+ (BOOL)updateViewCountForId:(NSString *)appID {
    NSString* url = [NSString stringWithFormat:@"http://mobile.mho.vn/services/gameex?type=incview&g=%@&key=%@", appID, kServerKey];

    NSString* retVal = [ServiceLib sendGetRequest:url];

    if (retVal) {
        SBJsonParser* parser = [[SBJsonParser alloc] init];
        id data = [parser objectWithString:retVal];
        if (data && [data isKindOfClass:[NSDictionary class]]) {
            NSNumber* result = [data objectForKey:@"Ret"];
            if (result && result.intValue == 1) {
                return YES;
            }
        }
    }

    return NO;
}
@end
